package com.ocom.exposeapi.aspect;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.utils.ResultUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;

@Aspect
@Component
public class GkdServiceAspect {

	private Logger log = LoggerFactory.getLogger(GkdServiceAspect.class);

	//切入点
	@Around("execution(* com.ocom.exposeapi.controller.GkdController.*(..)) && args(.., bindingResult) " +
			"|| execution (* com.ocom.exposeapi.controller.PlatformController.loginAuth(..))&& args(.., bindingResult)  "
			)
	public Object handleControllerMethod(ProceedingJoinPoint pjp, BindingResult bindingResult) throws Throwable {

		if (bindingResult.hasErrors()) {
			return ResultUtil.info(500,bindingResult.getAllErrors().get(0).getDefaultMessage());
		}



		Object result;

		// 类名
		String className = pjp.getTarget().getClass().getName();
		//方法名
		String methodName = pjp.getSignature().getName();
		try {
			Object[] args = pjp.getArgs();

			Object object=args[0];

			JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(object));

			Long timestamp = jsonObject.getLong("timestamp");

			Long currentT = System.currentTimeMillis();
			System.out.println(currentT);
			if(Math.abs(timestamp-currentT)>60000l){
				return ResultUtil.info(500,"非法时间戳");
			}

			result = pjp.proceed();

			log.info("类 【{}】 方法 【{}】 参数 【{}】 返回 【{}】", className, methodName, jsonObject, result);

			return result;
		} catch (Exception e) {
			log.info("请求URL:,切面异常:【{}】【{}】【{}】",className,methodName, e);
			//要返回的对象
			return ResultUtil.error(ResultEnum.Err_4003);
		}
	}


}
